package com.cbd.basic.leetcode.easy;

import com.alibaba.fastjson.JSON;
import com.cbd.basic.leetcode.ListNode;
import lombok.extern.slf4j.Slf4j;

/**
 * 合并两个有序链表
 * 设置一个头节点，然后分别遍历两个链表，比较节点值的大小，小的那个挂在新链表的结尾
 */
@Slf4j
public class Solution21 {
    public static void main(String[] args) {
        // list1: 1 -> 2 -> 4
        // list2: 1 -> 3 -> 4
        // merge: 1 -> 1 -> 2 -> 3 -> 4 -> 4
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(2, node1);
        ListNode node3 = new ListNode(1, node2);

        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(3, node4);
        ListNode node6 = new ListNode(1, node5);

        ListNode result = mergeTwoLists(node3, node6);
        log.info("result = {}", JSON.toJSONString(result));
        while (result != null) {
            log.info("val = {}", result.val);
            result = result.next;
        }
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode headNode = new ListNode();
        ListNode tailNode = headNode;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                tailNode.next = list1;
                list1 = list1.next;
            } else {
                tailNode.next = list2;
                list2 = list2.next;
            }
            tailNode = tailNode.next;
        }
        tailNode.next = list1 == null ? list2 : list1;
        return headNode.next;
    }
}
